package com.ruoyi.yljf.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.yljf.domain.CoursePackage;
import com.ruoyi.yljf.domain.ScoreType;
import com.ruoyi.yljf.domain.User;
import com.ruoyi.yljf.domain.dto.CreateDTO.RecordCreateDTO;
import com.ruoyi.yljf.domain.dto.RecordDTO;
import com.ruoyi.yljf.domain.enums.yljfEnums;
import com.ruoyi.yljf.domain.vo.RecordVO;
import com.ruoyi.yljf.mapper.CoursePackageMapper;
import com.ruoyi.yljf.mapper.ScoreTypeMapper;
import com.ruoyi.yljf.mapper.UserMapper;
import com.ruoyi.yljf.service.IUserScoreRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.yljf.mapper.RecordMapper;
import com.ruoyi.yljf.domain.Record;
import com.ruoyi.yljf.service.IRecordService;

import javax.annotation.Resource;

/**
 * 学习记录Service业务层处理
 * 
 * @author TAT
 * @date 2025-03-10
 */
@Service
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements IRecordService {

	@Resource
    private RecordMapper recordMapper;
	@Resource
	private CoursePackageMapper coursePackageMapper;
	@Resource
	private ScoreTypeMapper scoreTypeMapper;
	@Resource
	private UserMapper userMapper;
	@Resource
	private IUserScoreRecordService userScoreRecordService;
	/**
     * 查询学习记录列表
     * 
     * @param record 学习记录
     * @return 学习记录
     */
    @Override
    public List<Record> selectRecordList(Record record) {
    	LambdaQueryWrapper<Record> queryWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotNull(record.getTotalTime())) {
			queryWrapper.eq(Record::getTotalTime, record.getTotalTime());
		}
        if (StringUtils.isNotNull(record.getOffTime())) {
			queryWrapper.eq(Record::getOffTime, record.getOffTime());
		}
        if (StringUtils.isNotNull(record.getCourseId())) {
			queryWrapper.eq(Record::getCourseId, record.getCourseId());
		}
        if (StringUtils.isNotEmpty(record.getProgress())) {
			queryWrapper.eq(Record::getProgress, record.getProgress());
		}
        if (StringUtils.isNotNull(record.getSectionId())) {
			queryWrapper.eq(Record::getSectionId, record.getSectionId());
		}
        if (StringUtils.isNotNull(record.getUserId())) {
			queryWrapper.eq(Record::getUserId, record.getUserId());
		}
        if (StringUtils.isNotEmpty(record.getType())) {
			queryWrapper.eq(Record::getType, record.getType());
		}
        return recordMapper.selectList(queryWrapper);
    }

	@Override
	public List<RecordVO> recordByType(RecordDTO dto) {
		Record r = new Record(null,null,null,null,null,null,SecurityUtils.getUserId(),dto.getType());
		List<RecordVO> recordVOS  = recordMapper.queryRecordByType(r);
				return recordVOS;

	}

	@Override
	public List<RecordVO> addRecord(RecordCreateDTO dto) {
		Record record = new Record(dto);
		record.setProgress(String.valueOf(this.calculateProgress(dto.getTotalTime(),record.getOffTime())));
		record.setUserId(SecurityUtils.getUserId());
		Record record1 = recordMapper.selectOne(
				new LambdaQueryWrapper<>(Record.class)
						.eq(Record::getCourseId, dto.getCourseId())
						.eq(Record::getUserId, SecurityUtils.getUserId())
						.eq(Record::getSectionId, dto.getSectionId())
						.eq(Record::getType, dto.getType())
		);
		if (ObjectUtils.isNotEmpty(record1)) {
			if(!record1.getTotalTime().equals(record1.getOffTime())) {  // 有观看记录，但是观看是未看完时：更新观看记录
				record.setId(record1.getId());
				recordMapper.updateById(record);
			}
		}else {
			recordMapper.insert(record);
		}

		if(record1 != null && record1.getTotalTime().equals(record1.getOffTime())) {  // 有过观看记录且观看完成，不做添加积分
			return Collections.emptyList();
		}
		else if(dto.getTotalTime() != null && dto.getOffTime() != null && dto.getTotalTime().equals(dto.getOffTime())) { // 观看观察完成，添加积分
			// 根据type查询ScoreType对象
			// 使用scoreTypeMapper.selectOne方法，通过LambdaQueryWrapper查询type为 ”学习结束“的ScoreType对象
			ScoreType scoreType = scoreTypeMapper.selectOne(
					new LambdaQueryWrapper<>(ScoreType.class)
							.eq(ScoreType::getType, "学习结束")
			);

			// 调用IUserScoreRecordService的addUserScore方法，传入查询的ScoreType对象
			User user = userMapper.selectById(SecurityUtils.getUserId());
			userScoreRecordService.adduserScore(user, scoreType);
		}


		return Collections.emptyList();
	}


	@Override
	public List<RecordVO> recordByType(List<RecordVO> recordVOS,String type) {
		Record r = new Record(null,null,null,null,null,null,SecurityUtils.getUserId(),type);
		r.setUserId(SecurityUtils.getUserId());
		r.setType(type);
//		List<RecordVO> recordVOS = new ArrayList<>();
		switch (type){
			case "book":
				recordVOS = recordMapper.BookRecord(r);
				return recordVOS;
			case "video":
//				recordVOS = recordMapper.BookRecord(r);
				if ( ObjectUtils.isNotEmpty(recordVOS) ) {
					List<Long> ids = recordVOS.parallelStream()
							.map(RecordVO::getSectionId)
							.collect(Collectors.toList());
					List<CoursePackage> packageList = coursePackageMapper.selectBatchIds(ids);
					// 3. 构建ID到对象的映射
					Map<Long, CoursePackage> idToPackageMap = packageList.stream()
							.collect(Collectors.toMap(
									CoursePackage::getId,
									Function.identity(),
									(existing, replacement) -> existing));  // 处理重复ID
					// 4. 批量赋值
					recordVOS.forEach(record -> {
						CoursePackage pkg = idToPackageMap.get(record.getSectionId());
						if (pkg != null) {
							record.setName(pkg.getTitle());     // 设置title
							record.setImg(pkg.getImgUrl());  // 设置imgUrl
						}
					});
				}
				return recordVOS;
			case "audio":
//				recordVOS = recordMapper.VideoOrAudioRecord(r);
//				return recordVOS;
//				recordVOS = recordMapper.BookRecord(r);
				if ( ObjectUtils.isNotEmpty(recordVOS) ) {
					List<Long> ids = recordVOS.parallelStream()
							.map(RecordVO::getSectionId)
							.collect(Collectors.toList());
					List<CoursePackage> packageList = coursePackageMapper.selectBatchIds(ids);
					// 3. 构建ID到对象的映射
					Map<Long, CoursePackage> idToPackageMap = packageList.stream()
							.collect(Collectors.toMap(
									CoursePackage::getId,
									Function.identity(),
									(existing, replacement) -> existing));  // 处理重复ID
					// 4. 批量赋值
					recordVOS.forEach(record -> {
						CoursePackage pkg = idToPackageMap.get(record.getSectionId());
						if (pkg != null) {
							record.setName(pkg.getTitle());     // 设置title
							record.setImg(pkg.getImgUrl());  // 设置imgUrl
						}
					});
				}
				return recordVOS;
			case "practise":
				//TODO 学习记录-考试记录待添加
				recordVOS = recordMapper.VideoOrAudioRecord(r);
			default:
				throw new RuntimeException("类型错误");
		}
	}

	/**
	 * 计算答题进度（基于题数）
	 * @return 进度百分比（0.0 ~ 1.0）
	 */
	public double calculateProgress(Long totalTime,Long offTime) {
		// 基础校验
		if (totalTime == null || totalTime <= 0 || offTime == null || offTime < 0) {
			return 0.0;
		}

		// 计算原始进度（0.0~1.0）
		double rawProgress = Math.min(1.0,  (double) offTime / totalTime);

		// 向上取两位小数（使用Math.ceil ）
		double roundedProgress = Math.ceil(rawProgress  * 100) / 100;

		// 确保不超过100%
		return Math.min(roundedProgress,  1.0);
	}
}
